using UnityEngine;

namespace HEFramework
{
    /// <summary>
    ///
    /// 安全区域调整行为
    /// 
    /// ----------------------------------------
    /// 作者 hep
    /// 创建时间：2023-01-19 18:17:15
    /// ----------------------------------------
    /// </summary>
    [RequireComponent(typeof(RectTransform))]
    public class SafeAreaBehaviour : MonoBehaviour
    {
        private RectTransform rectTransform;
        private Rect lastSafeArea;


        private void Awake()
        {
            lastSafeArea = new Rect(0, 0, 0, 0);
            rectTransform = GetComponent<RectTransform>();
            Refresh();
        }

        private void Update()
        {
            Refresh();
        }

        private void Refresh()
        {
            Rect safeArea = Screen.safeArea;
            if (safeArea != lastSafeArea)
            {
                ApplySafeArea(safeArea);
            }
        }

        private void ApplySafeArea(Rect _r)
        {
            lastSafeArea = _r;
            // Convert safe area rectangle from absolute pixels to normalised anchor coordinates
            Vector2 anchorMin = _r.position;
            Vector2 anchorMax = _r.position + _r.size;
            anchorMin.x /= Screen.width;
            anchorMin.y /= Screen.height;
            anchorMax.x /= Screen.width;
            anchorMax.y /= Screen.height;
            rectTransform.anchorMin = anchorMin;
            rectTransform.anchorMax = anchorMax;
        }
    }
}